#coding:UTF-8
import datetime
import json
import sys

import pandas as pd
import numpy as np
np.set_printoptions(threshold=np.inf)
pd.set_option('display.max_columns', 1000)
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 1000)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
'''
在无开门状况下，化霜加热器启动到结束化霜时刻，冷冻蒸发器最高温度值小于0℃为故障。
'''
def jiareqi_guzhang(file_path):
    data0 = pd.read_csv(file_path)
    data = data0[(data0['timestamp'] >= '2022-01-01') & (data0['timestamp'] <= '2023-01-01')]
    m = data.loc[:, ['sn', 'timestamp', 'freezeroomsensortempreture', 'compressorstatus', 'freezeheat',
                     'freezeroomevaporationsensortempreture', 'colddoor', 'changingdoor', 'freezedoorb', 'freezedoora']]
    m = m.fillna(0)
    data = m
    m1 = data.loc[:, ["sn"]]  # zzfld00000b sn
    sn_indexs = m1.drop_duplicates()["sn"]  # zzfld00000b sn
    error_file= []
    for index in sn_indexs:
        print("sn=========================================================:", index)
        data0 = m[(m['sn'] == index)]
        data0 = data0.drop_duplicates(keep='last', subset=['timestamp'])
        data = data0.sort_values(by='timestamp', ascending=True)
        data = data.reset_index(drop=True)
        f_list1 = []
        cnt0 = 0
        for i in range(0, len(data)-1):
            if data.iloc[i].values[4] == True and (data.iloc[i].values[6] ==0 and data.iloc[i].values[7] ==0 and data.iloc[i].values[8] ==0 and data.iloc[i].values[9] ==0):
                f_list1.append(data.iloc[i,[1,4,5]].values)
            else:
                if len(f_list1) > 5:
                    f_data1 = np.array(f_list1)
                    #f_time_l = (datetime.datetime.strptime(f_data1[:, 0][-2],"%Y-%m-%d %H:%M:%S") - datetime.datetime.strptime(f_data1[:, 0][0],"%Y-%m-%d %H:%M:%S")).seconds / 3600
                    if np.max(f_data1[:, 2]) < 0:#>=(f_data1.shape[0]* ratio ):
                        cnt0 +=1
                f_list1 = []
        if cnt0 >= 10:
            if index not in error_file:
                error_file.append(index)
    print ("error_file:", error_file)
    print("len:", len(error_file))

if __name__ == "__main__":
    # 传入json格式
    if len(sys.argv) > 1:
        input = json.loads(sys.argv[1])
    else:
        input = {}
        # 默认运行起始日期
    date_start = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    # 默认运行结束日期
    date_end = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    # 默认物料号 where 过滤条件，如果传入materials，按照传入物料号过滤，如果没有传入物料号，运行全部数据
    materials = ''
    if 'date_start' in input and input['date_start'] != '':
        date_start = input['date_start']
    if 'date_end' in input and input['date_start'] != '':
        date_end = input['date_end']
    if 'materials' in input and input['date_start'] != '':
        materials = input['materials']
    if not materials:
        material_clause = ''
    else:
        ms = "','".join(materials.split(","))
        material_clause = f" and material in ('{ms}') "

    # sql where数据过滤语句
    where_clause = f" where p_date between '{date_start}' and '{date_end}' {material_clause} "


    # 示例
    sql = f""" select sn,p_date,timestamp from ods.iot_fridge  {where_clause} """
    print(sql)





    #
    #
    # stateMachineArn = sys.argv[1]
    # args =
    # run(stateMachineArn, args)
    # print("任务完成")
    #
    #
    # path = 'E:\\虹美\\专家系统\\基于规则的判断方法\\http分析516\\crmjiaoiot_jiareqiguzhang.csv'
    # jiareqi_guzhang(path)
    # print ("done!")
